# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import Context, loader, RequestContext
from django.http import HttpResponse

import string
import re
from snippet import *
import simplejson
from string import join
from urllib import quote

def renderQzoneCell(user, profile, oneblog, userpies, number, keywords, matchedarticleNum, rank, onlinestatus):
    title = oneblog.title
    content = oneblog.plaintext
    cat_name = oneblog.cat_name

    oneuserpie = None
    cat_names = []
    weights = []
    userpies.sort(key=lambda pie: pie.blog_ids.count('@@'), reverse=True) # sort on weight
    if userpies:
        for up in userpies:
            if up.cat_id == oneblog.cat_id:
                oneuserpie = up
            cat_names.append(up.cat_name)
            karr = up.blog_ids.split(u"@@")
            weights.append(len(karr) if karr else 0)

    cat_names_json = simplejson.dumps(cat_names)
    weights_json = simplejson.dumps(weights)
    #gcat_names = unicode(join([quote(e.encode('utf-8')) for e in cat_names], "|"), 'utf-8')
    #gweights = join([str(e) for e in weights], ",")

    # display the keywords
    if oneuserpie:
        piekeywords = oneuserpie.keywords.replace(u"@@", u" ")
    else:
        piekeywords = ""

    #display the pie and legend

    [mod_date, mod_time] = string.split(str(user.modtime), " ")
    place = profile.country + profile.province + profile.city if profile else ""
    marriage = profile.marriage if (profile and profile.marriage in [1, 2]) else None
    try:
        titlehtml = generate_snippet(title, keywords, maxlen=MAX_TITLE_LEN) or ""
        snippethtml = generate_snippet(content, keywords) or ""
    except Exception, e:
        titlehtml = title # fix
        snippethtml = content

    c = Context({'number': number,
         'odd': True if (number % 2) == 1 else False,
         'uid': user.uid,
         'uName': user.uName if user.uName else profile.nickname,
         'qzoneName': user.qzoneName,
         'qzoneDescription': user.qzoneDescription,
         'articleNum': user.articleNum,

         'age': profile.age if profile else None,
         'birthday': profile.birthday if profile else None,
         'place': place,
         'marriage': marriage,
         'career': profile.career if profile else None,

         'mod_date': mod_date,
         'titlehtml': titlehtml,
         'snippethtml': snippethtml,
         'matchedarticleNum': matchedarticleNum,
         'rank': rank,
         'onlinestatus': onlinestatus,

         'cat_name': cat_name,
         'piekeywords': piekeywords,

         'cat_names_json': cat_names_json,
         'weights_json': weights_json,

          #'gcat_names_json': gcat_names,
          #'gweights': gweights,
        })
    page = loader.get_template('qzonecell.html')
    return page.render(c)

def renderMsnCell(user, oneblog, userpies, number, keywords , matchedarticleNum, rank):
    [mod_date, mod_time] = string.split(str(user.modtime), " ")
    title = oneblog.title
    content = oneblog.plaintext
    cat_name = oneblog.cat_name
    sex = user.sex
    age = user.age
    birthday = user.birthday
    location = user.location
    job = user.job
    mail = user.mail
    info = user.info
    try:
        titlehtml = generate_snippet(title, keywords, maxlen=MAX_TITLE_LEN) or ''
        snippethtml = generate_snippet(content, keywords) or ''
    except Exception, e:
        titlehtml = title # fix 
        snippethtml = content

    oneuserpie = None
    karr = []
    weights = []
    cat_names = []
    if userpies:
        for up in userpies:
            if up.cat_id == oneblog.cat_id:
                oneuserpie = up
            cat_names.append(up.cat_name)
            karr = up.keywords.split(u'@@')
            weights.append(len(karr) if karr else 0)
    if oneuserpie:
        piekeywords = oneuserpie.keywords.replace(u'@@', ' ')
    else:
        piekeywords = ''
    cat_names_json = simplejson.dumps(cat_names)
    weights_json = simplejson.dumps(weights)

    empty_avatar_url = 'http://secure.wlxrs.com/$live.controls.images/ic/bluemannxl.png'
    c = Context({
              'number': number,
              'uid': user.uid,
              'familyname': user.familyname,
              'lastname': user.lastname,
              'rank' : rank,
              'matchedarticleNum' : matchedarticleNum,
              'info': user.info,
              'mod_date': mod_date,
              'titlehtml': titlehtml,
              'snippethtml': snippethtml,
              'cat_name': cat_name,
              'piekeywords':piekeywords,
              'sex': sex,
              'age':age,
              'birthday': birthday,
              'location': location,
              'job': job,
              'mail': mail,
              'info': info,
              'cat_names_json': cat_names_json,
              'weights_json': weights_json,
              'avatar_url': user.avatar,
              'empty_avatar_url': empty_avatar_url,
              })
    page = loader.get_template('msncell.html')
    return page.render(c)


def renderHead(needinfo=True, pagetype='qzone'):
    page = loader.get_template('head.html')
    return page.render(Context({'needinfo':needinfo, 'pagetype':pagetype}))

def renderFoot(selected = -1, type = 0):
    if type == 0:
        page = loader.get_template('foot.html')
    else:
        page = loader.get_template('foot2.html')
    c = Context({'selected': selected})
    return page.render( c )

def renderIndex(firsttry, adv):
    c = Context({'firsttry': firsttry, 'adv': adv})
    page = loader.get_template('index.html')
    return page.render(c)

def renderPlain(filename):
    page = loader.get_template(filename + '.html')
    return page.render(Context())

def renderFeedback(request):
    page = loader.get_template('feedback.html')
    return page.render(RequestContext(request))

def renderZhaorenme(h, f, c):
    c = Context({'header': h, 'footer': f, 'content': c})
    page = loader.get_template('zhaorenme.html')
    return page.render(c)
